import os
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout,QFileDialog
from PySide6.QtCore import  QThread
import json
import settings
from UIdata.index import Ui_MainWindow
# 自定义组件
from listener_component import MouseEvent
from processing_dialog import ProcessingDialog
from thread_work.engine_work import EngineWorker

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.connect_function()
        self.inint_Area()
        self.log_event = []

    def connect_function(self):
        """信号连接"""
        # 第一页
        self.ui.actionsad.triggered.connect(self.menu_)
        self.ui.pushButton.clicked.connect(self.pushButton_)
        # 第二页
        self.ui.pushButton_4.clicked.connect(self.mouseEvent_)
        self.ui.pushButton_7.clicked.connect(lambda :self.delete_component(self.ui.scrollArea.widget()))
        self.ui.pushButton_6.clicked.connect(self.start_key_mouse_chin_create_log)
    def inint_Area(self):
        """初始化滚动区域"""
        widgetArea = QWidget()
        lay_scroll = QVBoxLayout(widgetArea)               # 为内部容器创建垂直布局
        self.ui.scrollArea.setWidget(widgetArea)
        # 测试添加组件
        mouse_1 = MouseEvent()
        lay_scroll.addWidget(mouse_1)
        mouse_1.start_mouse_listener.connect(self.mainwindow_hide_show)

        lay_scroll.addStretch()
        self.ui.scrollArea.setWidgetResizable(True)
    def mainwindow_hide_show(self,signal):
        """窗口隐藏函数"""
        print(f'接受信号{signal}')
        if signal:
            self.hide()
        else:
            self.show()

    """首页逻辑"""
    def menu_(self):
        """首页按钮点击"""
        self.ui.stackedWidget.setCurrentIndex(0)
    def pushButton_(self):
        """开始使用按钮点击"""
        self.ui.stackedWidget.setCurrentIndex(1)

    """自定义添加组件逻辑"""
    def delete_component(self,widget):
        """删除容器的所有组件"""
        layout = widget.layout()
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget_to_delete = item.widget()
                if widget_to_delete is not None:
                    widget_to_delete.deleteLater()
        self.log_event = []
    def mouseEvent_(self):
        """创建鼠标控件"""
        lay_scroll = self.ui.scrollArea.widget().layout()            # 获取容器布局布局
        print("按钮被点击")
        new_com = MouseEvent()
        new_com.start_mouse_listener.connect(self.mainwindow_hide_show)

        if lay_scroll.count()>0 and lay_scroll.itemAt(lay_scroll.count()-1).spacerItem():
            end_index = lay_scroll.count()-1
            lay_scroll.insertWidget(end_index,new_com)               # 在指定位置添加
        else:
            lay_scroll.addWidget(new_com)
            lay_scroll.addStretch()
    def start_key_mouse_chin_create_log(self):
        """开始执行,保存记录"""
        father_widget = self.ui.scrollArea.widget()
        all_widgets = father_widget.findChildren(MouseEvent)
        print(len(all_widgets))
        while all_widgets:
            widget_obj = all_widgets.pop(0)
            print(widget_obj.info_dict)
            self.log_event.append(widget_obj.info_dict)

        # 保存运行日志文件
        file_path,selected_filter = QFileDialog.getSaveFileName(
            self,                                             # 父窗口
            '保存文件',                                  # 对话框标题
            settings.USER_PATH,                               # 默认路径和文件名
            "JSON文件 (*.json)",                          # 文件类型过滤器
        )
        if file_path:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(self.log_event, f, ensure_ascii=False, indent=4)
            print(f'保存成功{file_path}')

            # 创建对话框
            self.dialog = ProcessingDialog()
            self.start_thread_events(file_path)
        else:
            print('保存失败')
    def start_thread_events(self,file_path):
        """开始创建线程执行事件"""
        self.thread = QThread()
        self.worker = EngineWorker(file_path)
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.start)

        # 连接线程信号和槽函数
        self.worker.data_success.connect(self.data_success_)                  # 对话框更新
        self.worker.component_success.connect(self.component_success_)        # 对话框更新
        self.worker.start_engine.connect(self.start_engine_)                  # 引擎开始隐藏窗口

        # 线程结束后连接槽函数
        self.worker.finished.connect(self.finished_ok)                        # 线程结束显示窗口
        self.worker.finished.connect(self.worker.deleteLater)
        self.worker.finished.connect(self.thread.quit)
        self.thread.finished.connect(self.thread.deleteLater)

        # 线程开始
        self.thread.start()
        self.dialog.exec()
    def data_success_(self, signal):
        print('data_success_调用')
        if signal:
            self.dialog.update_message(message="数据处理成功")
        else:
            self.dialog.update_message(message="数据处理失败")
    def component_success_(self, signal):
        print('component_success_调用')
        if signal:
            self.dialog.update_message(message="组件生成成功,5秒后开始执行")
        else:
            self.dialog.update_message(message="组件生成失败")
    def start_engine_(self,signal):
        if signal == 0:
            self.dialog.close()
            self.mainwindow_hide_show(True)
        else:
            self.dialog.update_message(message=f"开始执行!倒计时{signal}...")
    def finished_ok(self):
        """线程结束"""
        self.mainwindow_hide_show(False)






if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())